package update;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobstoreFailureException;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
public class UpdateMultipleFiles extends HttpServlet  {

	private static DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, BlobstoreFailureException {
		//String[] keys = new String[100];
		String keys = req.getParameter("selectListKeys[]");		//getting the list of keys
		if (!keys.equals(null)) {
			String ablum = req.getParameter("albumName");
			String[] keysArray = keys.split(",");
			for(int i=0; i < keysArray.length; i++)
			{
				Key entityKey = KeyFactory.stringToKey(keysArray[i]);
				Entity file;
				
				try {
					file = datastore.get(entityKey);
					String type = (String) file.getProperty("contentType");
					if (type.equals("image")) { // image type files
						file.setProperty("album", ablum);
					} else if (type.equals("video")) { // video type files
						file.setProperty("collection", ablum);
					} else if (type.equals("audio")) { // audio type files
						file.setProperty("album", ablum);
					} else { // documents type files
						file.setProperty("album", ablum);
					}
					
					datastore.put(file);
				} catch (EntityNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		// redirect to a confirmation page
		resp.sendRedirect(req.getHeader("referer"));
	}
	
}
